//获取应用实例
var app = getApp()
var util = require('../../utils/util.js');

Page({
  data: {
    imgurl: '',
    searchWord: '',
    isTop: false,
    lastX: 0,// 滑动控制
    lastY: 0,
    currentGesture: 0,
    hh: 0,
    list: [],
    oldList: [],// 原始数据，未经筛选
    listType: 'list',
    total: 0,
    pageNum: 0,
    goodsGroupId: 0, // 产品分组
    sort: 'createTime',// 排序
    order: 'desc',
    goodGroupName: '',
    isShow: false,//显示内容
    showNoneRefresh: false,//刷新无更多
    showNoData: false, //无数据
    // 规格弹出层
    showLoadIngGg: true,
    isTrueGroup: false, // 是否开团
    goods: '', // 产品
    ggList: '', // 产品规格集合
    ggListArr: '', // 筛选规格
    ggValue0: '',
    ggValue1: '',
    ggValue2: '',
    isChoice: false,
    vaArr: [],
    goodsGg: {}, // 选中规格
    chPrice: '',
    onePrice: '', // 单价
    chStock: '',
    goodNum: '1',
    ddPrice: 0,
    ptPrice: 0,
    margin:3,
    width:168
  },
  onShareAppMessage: function (res) {
    var goodsId = this.data.goodsId
    return {
      title: ' ',
      path: '/pages/goods/goodsList',
      success: function (res) {
        console.log('转发成功了')
      },
      fail: function (res) {
        console.log('转发失败了')
      }
    }
  },
  onLoad: function (options) {
    try {
      var res = wx.getSystemInfoSync()
      var w=res.windowWidth-12;
      var margin = parseInt(w*0.01)
      var width = (w-margin*4)/2
      this.setData({ margin: margin, width: width, hh: res.windowHeight })
    } catch (e) {
      // Do something when catch error
    }
    //调用应用实例的方法获取全局数据
    var that = this
    if (app.shopConfig) {
      var shopConfig = app.shopConfig
      that.setData({ listType: shopConfig.goodsStyle })
    }
    that.setData({ imgurl: app.imageUrl })
    wx.showLoading({
      title: '加载中',
    })
    // 产品分组
    var groupId = options.groupId
    var groupName = options.groupName
    that.setData({ goodsGroupId: groupId, goodGroupName: groupName })
    if(parseInt(groupId) > 0){//设置标题
      wx.setNavigationBarTitle({
        title: groupName,
      })
    }
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 产品名称
    var gname = app.goodsListFilter //获取搜索页回传的值
    this.setData({ searchWord: gname })
    this.setData({ pageNum: 0, list: [], total: 0, showNoneRefresh: false, showNoData: false, isTop: false })
    this.loadData()
  },
  onHide: function () {
    // 页面隐藏
    app.goodsListFilter = ""
  },
  onUnload: function () {
    // 页面关闭
    app.goodsListFilter = ""
  },
  onPageScroll: function (e) {
    var he = e.scrollTop
    if (he < 10) {
      this.setData({ isTop: false })
    }
    if (he >= 10) {
      this.setData({ isTop: true })
    }
  },
  bindSearch: function (e) {
    wx.redirectTo({
      url: '../search/search'
    })
  },
  onPullDownRefresh: function () {
    this.setData({ pageNum: 0, list: [], total: 0, showNoneRefresh: false, isTop: false })
    this.loadData()
  },
  onReachBottom: function () {
    if (this.data.list.length < this.data.total) {
      this.loadData()
    } else {
      this.setData({ showNoneRefresh: true })
    }
  },
  tabClick: function (e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id,
      tabChecked: e.currentTarget.dataset.id
    });
  },
  // 滑动控制
  handletouchmove: function (event) {
    let currentX = event.touches[0].pageX
    let currentY = event.touches[0].pageY
    let tx = currentX - this.data.lastX
    let ty = currentY - this.data.lastY
    let text = ""
    //上下方向滑动
    if (Math.abs(tx) <= Math.abs(ty)) {
      if (ty < 0) {
        text = "向上滑动"
        this.data.currentGesture = 3
        this.setData({ isTop: true })
      } else if (ty > 0) {
        text = "向下滑动"
        // if (currentY <= parseFloat(this.data.hh*0.66)){
        //   this.setData({ isTop: false })
        // }
        this.data.currentGesture = 4
      } else if( ty == 0) {
        
      }
    }
  },

  handletouchtart: function (event) {
    this.data.lastX = event.touches[0].pageX
    this.data.lastY = event.touches[0].pageY
  },
  handletouchend: function (event) {
    this.data.currentGesture = 0
  },

  // 查询产品列表
  loadData() {
    var that = this
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    var num = that.data.pageNum + 1
    var groupId = that.data.goodsGroupId
    var params = {
      goodsGroupId: groupId,  pageIndex: num, pageSize: 6, 
      sort: that.data.sort, order: that.data.order, goodsName: that.data.searchWord
    }
    var encodingStr = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/cx/retail/getGoodsList.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        var templist = that.data.list
        console.log(rest)
        if (rest.isSuccess == 0) {
          if (rest.list != '' && rest.list != null) {
            for (var i = 0; i < rest.list.length; i++) {
              templist.push(rest.list[i])
            }
            // 排序
            that.setData({ oldList: templist })
            if (rest.needSort){
              that.sortByCondition()
            }
            that.setData({ list: templist, total: rest.total, pageNum: num })
            if (parseInt(groupId) > 0){
              that.setData({ goodGroupName: templist[0].goodsGroupName})
            }
          }
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
      },
      complete: function () {
        wx.stopPullDownRefresh()
        wx.hideLoading()
        that.setData({ isShow: true })
        var list = that.data.list
        if (list.length == 0) {
          that.setData({ showNoData: true })
        }
      }
    })
  },
  // 根据条件排序
  sortByCondition: function () {
    var that = this
    var sortList = that.data.oldList
    var sotrTy = that.data.sort
    if (sotrTy != '' && sotrTy != null) {
      if (sotrTy == 'createTime') {
      } else if (sotrTy == 'price') {
        sortList.sort(that.compare('price'))
      } else if (sotrTy == 'saleCount') {
        var orderTy = that.data.order
        if(orderTy == 'desc'){
          sortList.sort(that.compare('saleCount'))
        } else if (orderTy == 'asc'){
          sortList.sort(that.compare('saleCount')).reverse()
        }
      }
    }
    return sortList
  },
  // 数组排序
  compare: function (property) {
    return function (a, b) {
      var value1 = a[property];
      var value2 = b[property];
      return value1 - value2;
    }
  },
  // 排序
  bindToSort: function (e) {
    var ty = e.currentTarget.dataset.ty
    var sort = this.data.sort
    var order = this.data.order
    var sortty = '', orderty = ''
    if(ty == 'zh'){
      sortty = 'createTime'
      orderty = 'desc'
    }else if(ty == 'xl'){
      sortty = 'saleCount'
      orderty = 'desc'
    }else if(ty == 'jg'){
      sortty = 'price'
      if(order == 'desc'){
        orderty = 'asc'
      }else{
        orderty = 'desc'
      }
    }
    this.setData({ sort: sortty, order: orderty })
    this.setData({ pageNum: 0, list: [], total: 0, showNoneRefresh: false })
    this.loadData()
  },
  // 详情
  bindtoDetail:function (e) {
    var item = e.currentTarget.dataset.opt
    var goodsId = item.id
    wx.navigateTo({
      url: '../goods/goodDetail?id=' + goodsId
    })
  }
})
